import React, { useEffect } from 'react';
import { Tree  } from 'antd'
import ProvinceData from '@/utils/province'
import { connect } from 'dva';

const { TreeNode } = Tree;

const ProvinceTree = props => {
  const { type, trans, data = [] } = props
  const { current } = trans
  const selected = data.length >= current && data.length > 0 ? data[current].districtIds.split(',') : []
  const renderTreeNodes = data =>
    data.map(item => {
      if (item.subs) {
        return (
          <TreeNode title={item.name} key={item.id} dataRef={item}>
            {renderTreeNodes(item.subs)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.id} title={item.name} {...item} />;
    });
  const onCheck = (selectedKeys, info) => {
    
    if (type == 'free') {
      const { freeRecord, current } = props.trans
      const pro = []
      const newData = [...freeRecord]
      const item = newData[current];
      ProvinceData.map(p => {
        selectedKeys.map(k => p.id == k && pro.push(p.name))
      })
      newData.splice(current, 1, {
        ...item,
        districtNames: pro.toString(),
        districtIds: selectedKeys.toString()
      });
      props.dispatch({
        type: 'trans/update',
        payload: {
          freeId: selectedKeys,
          freeCity: pro.toString(),
          freeRecord: newData,
        }
      })
    } else {
      const { record, current } = props.trans
      const pro = []
      const newData = [...record]
      const item = newData[current];
      ProvinceData.map(p => {
        selectedKeys.map(k => p.id == k && pro.push(p.name))
      })
      newData.splice(current, 1, {
        ...item,
        districtNames: pro.toString(),
        districtIds: selectedKeys.toString()
      });
      props.dispatch({
        type: 'trans/update',
        payload: {
          proId: selectedKeys,
          proName: pro.toString(),
          record: newData,
        }
      })
    }
  }
  return (
    <Tree
      checkable
      onCheck={onCheck}
      defaultCheckedKeys={selected}
    >
      {renderTreeNodes(ProvinceData)}
    </Tree>
  );
};

export default connect(({trans}) => ({
  trans,
}))(ProvinceTree);